package com.huilai.platform.country_platform.service;

import com.huilai.platform.country_platform.core.AuditEnum;
import com.huilai.platform.country_platform.core.RecruitmentEnum;
import com.huilai.platform.country_platform.dto.RecruitmentDTO;
import com.huilai.platform.country_platform.dto.RecruitmentHasUserDTO;
import com.huilai.platform.country_platform.model.InformationRecruitment;
import com.huilai.platform.country_platform.model.PartyActivities;
import com.huilai.platform.country_platform.model.User;
import com.huilai.platform.country_platform.model.UserRecruitment;
import com.huilai.platform.country_platform.repository.AttractionsWaterscapeReposity;
import com.huilai.platform.country_platform.repository.InformationRecruitmentReposity;
import com.huilai.platform.country_platform.repository.UserRecruitmentReposity;
import com.huilai.platform.country_platform.repository.UserRepository;
import com.huilai.platform.country_platform.util.CookieUtil;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 作者：洪霓
 * 日期：2023/2/18
 * 注释：
 */
@Service
public class InformationService {

    @Autowired
    private InformationRecruitmentReposity informationRecruitmentReposity;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserRecruitmentReposity userRecruitmentReposity;

    public Page<InformationRecruitment> recruitmentListUI(String searchName, Pageable pageable) {
//        查询所有招工就业信息
        Page<InformationRecruitment> recruitmentPage = informationRecruitmentReposity.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add((cb.like(root.get("company"), "%" + searchName + "%")));
            }
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);
        return recruitmentPage;
    }

    public Page<RecruitmentDTO> recruitmentListUI2(String searchName, Pageable pageable) {
//        查询所有招工就业信息
        Page<InformationRecruitment> recruitmentPage = informationRecruitmentReposity.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(searchName)) {
                predicates.add((cb.like(root.get("company"), "%" + searchName + "%")));
            }
            predicates.add(cb.equal(root.get("auditStatus"),1));
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("updateTime")));
            return null;
        },pageable);

        Page<RecruitmentDTO> recruitmentDTOPage = recruitmentPage.map(informationRecruitment -> {
            RecruitmentDTO recruitmentDTO = new RecruitmentDTO(
                    informationRecruitment.getId(),
                    informationRecruitment.getCompany(),
                    informationRecruitment.getImage(),
                    informationRecruitment.getAddress(),
                    informationRecruitment.getTelephone(),
                    informationRecruitment.getName(),
                    RecruitmentEnum.getStringByStatus(informationRecruitment.getStatus()),
                    AuditEnum.getStringByStatus(informationRecruitment.getAuditStatus()),
                    informationRecruitment.getDescribe(),
                    informationRecruitment.getCreateTime(),
                    informationRecruitment.getUpdateTime()
            );
            return recruitmentDTO;
        });
        return recruitmentDTOPage;
    }
    public Page<RecruitmentDTO> auditPushRecruitmentListUI(HttpServletRequest request, Pageable pageable){
//        找到当前登录用户所发布的招工就业信息
        Cookie cookie = CookieUtil.get(request, "username");
        if (cookie == null) {
            throw new ServiceException("用户未登录");
        }
        User user = userRepository.findUserByUsername(cookie.getValue());
        List<InformationRecruitment> recruitmentList = informationRecruitmentReposity.findAuditInformationRecruitmentByUserId(user.getId());
        recruitmentList = recruitmentList.stream().sorted(Comparator.comparing(InformationRecruitment::getUpdateTime))
                .collect(Collectors.toList());
        Collections.reverse(recruitmentList);
        int start = (int) pageable.getOffset();
        int end = (start + pageable.getPageSize()) > recruitmentList.size() ? recruitmentList.size() : (start + pageable.getPageSize());
        Page<InformationRecruitment>recruitmentPage = new PageImpl<>(recruitmentList.subList(start, end), pageable, recruitmentList.size());
        Page<RecruitmentDTO> recruitmentDTOPage = recruitmentPage.map(informationRecruitment -> {
            RecruitmentDTO recruitmentDTO = new RecruitmentDTO(
                    informationRecruitment.getId(),
                    informationRecruitment.getCompany(),
                    informationRecruitment.getImage(),
                    informationRecruitment.getAddress(),
                    informationRecruitment.getTelephone(),
                    informationRecruitment.getName(),
                    RecruitmentEnum.getStringByStatus(informationRecruitment.getStatus()),
                    AuditEnum.getStringByStatus(informationRecruitment.getAuditStatus()),
                    informationRecruitment.getDescribe(),
                    informationRecruitment.getCreateTime(),
                    informationRecruitment.getUpdateTime()
            );
            return recruitmentDTO;
        });

        return recruitmentDTOPage;
    }


    public Page<RecruitmentDTO> pushRecruitmentListUI(HttpServletRequest request, Pageable pageable){
//        找到当前登录用户所发布的招工就业信息
        Cookie cookie = CookieUtil.get(request, "username");
        if (cookie == null) {
            throw new ServiceException("用户未登录");
        }
        User user = userRepository.findUserByUsername(cookie.getValue());
        List<InformationRecruitment> recruitmentList = informationRecruitmentReposity.findInformationRecruitmentByUserId(user.getId());
        recruitmentList = recruitmentList.stream().sorted(Comparator.comparing(InformationRecruitment::getUpdateTime))
                .collect(Collectors.toList());
        Collections.reverse(recruitmentList);
        int start = (int) pageable.getOffset();
        int end = (start + pageable.getPageSize()) > recruitmentList.size() ? recruitmentList.size() : (start + pageable.getPageSize());
        Page<InformationRecruitment>recruitmentPage = new PageImpl<>(recruitmentList.subList(start, end), pageable, recruitmentList.size());
//        Page<InformationRecruitment> recruitmentPage = informationRecruitmentReposity.findAll((root, query, cb) -> {
//            List<Predicate> predicates = new ArrayList<>();
//            //攻略name模糊查询
//            predicates.add((cb.equal(root.get("user"), user)));
//            //攻略name模糊查询
//            if (!StringUtils.isEmpty(searchName)) {
//                predicates.add((cb.like(root.get("name"), "%" + searchName + "%")));
//            }
//            query.where(predicates.toArray(new Predicate[]{}));
//            query.orderBy(cb.desc(root.get("createDate")));
//            return null;
//        }, pageable);
        Page<RecruitmentDTO> recruitmentDTOPage = recruitmentPage.map(informationRecruitment -> {
            RecruitmentDTO recruitmentDTO = new RecruitmentDTO(
                    informationRecruitment.getId(),
                    informationRecruitment.getCompany(),
                    informationRecruitment.getImage(),
                    informationRecruitment.getAddress(),
                    informationRecruitment.getTelephone(),
                    informationRecruitment.getName(),
                    RecruitmentEnum.getStringByStatus(informationRecruitment.getStatus()),
                    AuditEnum.getStringByStatus(informationRecruitment.getAuditStatus()),
                    informationRecruitment.getDescribe(),
                    informationRecruitment.getCreateTime(),
                    informationRecruitment.getUpdateTime()
            );
            return recruitmentDTO;
        });

        return recruitmentDTOPage;
    }

    public Integer addRecruitment(HttpServletRequest request, InformationRecruitment informationRecruitment){
//        发布招工就业信息
        Cookie cookie = CookieUtil.get(request, "username");
        if (cookie == null) {
            throw new ServiceException("用户未登录");
        }
        User user = userRepository.findUserByUsername(cookie.getValue());
        if (informationRecruitment.getImage().equals("example")){
            informationRecruitment.setImage(null);
        }
        Integer integer = informationRecruitmentReposity.addRecruitment(informationRecruitment);
//        InformationRecruitment informationRecruitment1 = informationRecruitmentReposity.findInformationRecruitmentByDescribe(informationRecruitment.getDescribe());
        InformationRecruitment informationRecruitment1 = informationRecruitmentReposity.findInformationRecruitmentByDescribe(informationRecruitment.getDescribe());
        userRecruitmentReposity.addUserRecruitment(user.getId(), informationRecruitment1.getId());
        return integer;
    }
    public Integer addAdminRecruitment(InformationRecruitment informationRecruitment, HttpSession session){
//        发布招工就业信息
        if (informationRecruitment.getImage().equals("example")){
            informationRecruitment.setImage(null);
        }
        User user = (User)session.getAttribute("user");
        User user1 = userRepository.findUserByUsername(user.getUsername());
        Integer integer = informationRecruitmentReposity.addRecruitmentAll(informationRecruitment);
        InformationRecruitment informationRecruitment1 = informationRecruitmentReposity.findInformationRecruitmentByDescribe(informationRecruitment.getDescribe());
        userRecruitmentReposity.addUserRecruitment(user1.getId(), informationRecruitment1.getId());
        return integer;
    }

    public Integer updateRecruitment(InformationRecruitment informationRecruitment){
        if (informationRecruitment.getImage().equals("example")){
            informationRecruitment.setImage(null);
        }
        Integer integer = informationRecruitmentReposity.updateRecruitment(informationRecruitment);
        return integer;
    }

    public Integer deleteRecruitmentById(Integer id){
        Integer integer = informationRecruitmentReposity.deleteRecruitmentById(id);
        UserRecruitment userRecruitment = userRecruitmentReposity.findUserRecruitmentByRecruitmentId(id);
        if(userRecruitment != null){
            Integer integer1 = userRecruitmentReposity.deleteUserRecruitment(userRecruitment.getId());
        }
        if(integer == 1&&integer == 1){
            return 1;
        }
        return -1;
    }

    public Integer updateRecruitmentAll(InformationRecruitment informationRecruitment){
        Integer integer = informationRecruitmentReposity.updateRecruitmentAll(informationRecruitment);
        return integer;
    }
    public Integer changeRecruitmentAuditStatusById(Integer id, Integer auditSatus){
        Integer integer = informationRecruitmentReposity.updateAuditStatus(id, auditSatus);
        return integer;
    }

    public RecruitmentHasUserDTO getRecruitmentHasUserDTOById(Integer id){
        InformationRecruitment informationRecruitment = informationRecruitmentReposity.getOne(id);
        UserRecruitment userRecruitment = userRecruitmentReposity.findUserRecruitmentByRecruitmentId(id);
        String userName = "管理员";
        if (userRecruitment != null){
            userName = userRepository.findUserById(userRecruitment.getUserId()).getUsername();
        }
        RecruitmentHasUserDTO recruitmentHasUserDTO = new RecruitmentHasUserDTO(
                informationRecruitment.getId(),
                userName,
                informationRecruitment.getCompany(),
                informationRecruitment.getImage(),
                informationRecruitment.getAddress(),
                informationRecruitment.getTelephone(),
                informationRecruitment.getName(),
                RecruitmentEnum.getStringByStatus(informationRecruitment.getStatus()),
                AuditEnum.getStringByStatus(informationRecruitment.getAuditStatus()),
                informationRecruitment.getDescribe(),
                informationRecruitment.getCreateTime(),
                informationRecruitment.getUpdateTime()
        );
        return recruitmentHasUserDTO;
    }

    public InformationRecruitment findRecruitmentById(Integer id){
        return informationRecruitmentReposity.findById(id).orElseThrow(() -> new ServiceException("招工就业信息id错误!"));
    }

    public Boolean isPushUser(Integer id, HttpServletRequest request){
//        判断是否为发布人
        Cookie cookie = CookieUtil.get(request, "username");
        if (cookie == null) {
            throw new ServiceException("用户未登录");
        }
        User user = userRepository.findUserByUsername(cookie.getValue());
        UserRecruitment userRecruitment = userRecruitmentReposity.findUserRecruitmentByUserIdAndRecruitmentId(user.getId(), id);
        if (userRecruitment == null){
            return false;
        }else {
            return true;
        }
    }

    public UserRecruitment findUserRecruitmentByRecruitmentId(Integer id){
        return userRecruitmentReposity.findUserRecruitmentByRecruitmentId(id);
    }

    public Integer updateUserRecruitment(Integer id, String describe){
        return userRecruitmentReposity.updateUserRecruitment(id, describe);
    }

//    public Integer updateUserRecruitment(UserRecruitment userRecruitment){
//        return userRecruitmentReposity.updateUserRecruitment(userRecruitment);
//    }
}
